package org.example;

import bean.DB;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/updateBasicInfoServlet")
public class updateBasicInfoServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userIdStr = (String) request.getSession().getAttribute("userId");
        String newUsername = request.getParameter("username");
        String newGender = request.getParameter("gender");
        String newBirthday = request.getParameter("birthday");

        // 检查必要字段是否为空
        if (userIdStr == null || newUsername == null || newUsername.trim().isEmpty() ||
                newGender == null || newGender.trim().isEmpty() ||
                newBirthday == null || newBirthday.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "用户ID、用户名、性别或生日不能为空");
            return;
        }

        int userId = Integer.parseInt(userIdStr);

        try (Connection conn = new DB().createConn()) {
            // 更新用户基本信息的SQL语句
            String updateProfileSql = "UPDATE users SET username = ?, gender = ?, birthday = ? WHERE id = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(updateProfileSql)) {
                pstmt.setString(1, newUsername);
                pstmt.setString(2, newGender);
                pstmt.setString(3, newBirthday); // 如果数据库中生日是日期类型，请考虑转换格式
                pstmt.setInt(4, userId);

                int rowsAffected = pstmt.executeUpdate();
                if (rowsAffected > 0) {
                    response.sendRedirect("userPage.jsp");  // 基本信息更新成功，重定向回个人页面
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新用户基本信息失败");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误");
        }
    }
}
